package com.demo.qqClient.service;

import com.demo.qqcommon.Message;
import com.demo.qqcommon.MessageType;
import org.junit.Test;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author gy
 * @date 2022/5/7
 * 该类/对象，提供消息相关的服务方法
 */
public class MessageClientService {

    /**
     * 群发消息
     * @param content
     * @param senderId
     */
    public void sendMessageToAll(String content,String senderId){
        // 创建msg对象
        Message msg = new Message();
        // 普通的聊天的消息
        msg.setMsgType(MessageType.MESSAGE_TO_ALL_MES);
        msg.setContent(content);
        msg.setSender(senderId);
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        msg.setSentTime(currentTime);

        System.out.println(currentTime+ " " + senderId + " 对 " + "大家" + " 说 " + content);

        try {
            // 拿到当前用户 对应的 对象输出流
            Socket socket = ManageClientConnectServerThread.getClientConnectServerThread(senderId).getSocket();
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            // 将信息发送出去
            oos.writeObject(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 私聊
     * @param content
     * @param senderId
     * @param getterId
     */
    public void sendMessageToOne(String content,String senderId,String getterId){
        // 创建msg对象
        Message msg = new Message();
        // 普通的聊天的消息
        msg.setMsgType(MessageType.MESSAGE_COMM_MES);
        msg.setContent(content);
        msg.setSender(senderId);
        msg.setGetter(getterId);
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        msg.setSentTime(currentTime);

        System.out.println(senderId + " 对 " + getterId + " 说 " + content);

        try {
            // 拿到当前用户 对应的 对象输出流
            Socket socket = ManageClientConnectServerThread.getClientConnectServerThread(senderId).getSocket();
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            // 将信息发送出去
            oos.writeObject(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试时间
     */
    @Test
    public void m1(){
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println(currentTime);
    }
}
